import * as actions from './';

import HttpRequest from './../common/http';

const rootUrl = window.restConfig.rootUrl;

export const getAppointments = (code, periodId) => {
  return (dispatch, getState) => {
    HttpRequest.get(rootUrl + '/appoint/appointments/' + code + (periodId?('?periodId='+periodId):''))
      .then((ret) => {
        dispatch({
          type: actions.APPOINT_CHANGE,
          data: {
            data: ret.data.data
          }
        })
        dispatch({
          type: actions.APPOINT_CHANGE,
          data: {
            page: ret.data.page
          }
        })
      }).catch((err) => {
        dispatch(showError('加载数据失败'));
      });
  }
}
export const moreAppoints = () => {
  return (dispatch, getStore) => {
    let state = getStore().appoint || {};
    HttpRequest.get(rootUrl + '/appoint/more/appointments')
      .then((ret) => {
        let newData = state.data;
        let keys = (ret.data&&ret.data.data&&Object.keys(ret.data.data)) || [];
        keys.forEach( (key) => {
          if (newData[key]) {
            newData[key] = newData[key].concat(ret.data.data[key]);
          } else {
            newData[key] = ret.data.data[key];
          }
        })
        dispatch({
          type: actions.APPOINT_CHANGE,
          data: {
            data: newData
          }
        })
        dispatch({
          type: actions.APPOINT_CHANGE,
          data: {
            page: ret.data.page
          }
        })
      }).catch((err) => {
        dispatch(showError('加载数据失败'));
      });
  }
}

export const doAppoint = (periodId, beginTime) => {
  return (dispatch) => {
    HttpRequest.get(rootUrl + '/appoint/doappoint')
      .then((ret) => {
        if (ret.step&&ret.step === -1) {
          dispatch(stateChange('doBind', true));
        } else {
          dispatch({
            type: actions.APPOINT_CHANGE,
            data: {
              state: {
                ...ret.data,
                step: ret.step,
                periodId: periodId,
                beginTime: beginTime
              }
            }
          })
        }
      }).catch((err) => {
        dispatch(showError(err.message));
      });
  }
}
export const errorChange = (name, value) => {
  return {
    type: actions.APPOINT_CHANGE,
    data: {
      error: {
        [name]: value
      }
    }
  }
}

export const stateChange = (name, value) => {
  return {
    type: actions.APPOINT_CHANGE,
    data: {
      state: {
        [name]: value
      }
    }
  }
}

export const showError = (text) => {
  return (dispatch) => {
    dispatch(errorChange('hasError', true));
    dispatch(errorChange('msg', text));

    let timer = setTimeout( () => {
      window.clearTimeout(timer);
      dispatch(errorChange('hasError', false));
      dispatch(errorChange('msg', ''));
    }, 2000);
  }
}